<template>
  <div v-if="show" class="modal-overlay" @click="$emit('update:show', false)">
    <div class="modal-content register-modal" @click.stop>
      <!-- 高级背景效果 -->
      <div class="background-effects">
        <div class="gradient-orbs">
          <div class="orb orb-1"></div>
          <div class="orb orb-2"></div>
          <div class="orb orb-3"></div>
        </div>
        <div class="grid-pattern"></div>
      </div>

      <div class="modal-header">
        <div class="logo-container">
          <div class="logo-wrapper">
            <!-- 艺术感图标 -->
            <div class="logo-icon artistic-icon">
              <div class="icon-shape">
                <div class="fitness-symbol">
                  <div class="weight-circle"></div>
                  <div class="energy-wave"></div>
                  <div class="motion-line"></div>
                </div>
              </div>
            </div>
            <div class="logo-text">
              <h1>FitPro</h1>
              <span>用户注册</span>
            </div>
          </div>
        </div>
        <div class="welcome-text">
          <h2>加入我们</h2>
          <p>创建您的健身账户</p>
        </div>
        <button class="close-btn" @click="$emit('update:show', false)">&times;</button>
      </div>

      <form @submit.prevent="handleSubmit" class="login-form">
        <div class="form-group">
          <div class="input-container">
            <div class="input-icon">
              <i class="fas fa-phone"></i>
            </div>
            <input
                id="reg-mobile"
                v-model="registerForm.mobile"
                type="text"
                class="form-input"
                placeholder="请输入手机号"
                required
            />
            <div class="input-border"></div>
            <div class="input-highlight"></div>
          </div>
        </div>

        <div class="form-group">
          <div class="input-container">
            <div class="input-icon">
              <i class="fas fa-lock"></i>
            </div>
            <input
                id="reg-password"
                v-model="registerForm.password"
                type="password"
                class="form-input"
                placeholder="请输入密码（至少6位）"
                required
            />
            <div class="input-border"></div>
            <div class="input-highlight"></div>
          </div>
        </div>

        <div class="form-group">
          <div class="input-container">
            <div class="input-icon">
              <i class="fas fa-user"></i>
            </div>
            <input
                id="reg-nickname"
                v-model="registerForm.nickname"
                type="text"
                class="form-input"
                placeholder="请输入昵称"
                required
            />
            <div class="input-border"></div>
            <div class="input-highlight"></div>
          </div>
        </div>

        <div class="form-buttons">
          <button type="submit" class="login-button" :class="{ 'loading': isLoading }">
            <span class="button-text" v-if="!isLoading">
              <i class="fas fa-user-plus"></i>
              立即注册
            </span>
            <span class="button-loading" v-else>
              <i class="fas fa-spinner fa-spin"></i>
              注册中...
            </span>
            <div class="button-shine"></div>
          </button>
          <button type="button" class="register-btn" @click="showLogin">
            <i class="fas fa-sign-in-alt"></i>
            去登录
          </button>
        </div>
      </form>

      <!-- 消息提示框部分 -->
      <div v-if="errorMessage || successMessage"
           class="message-box"
           :class="successMessage ? 'success-message' : 'error-message'">
        <div class="message-icon">
          <i :class="successMessage ? 'fas fa-check-circle' : 'fas fa-exclamation-triangle'"></i>
        </div>
        <span>{{ successMessage || errorMessage }}</span>
      </div>

      <!-- 底部信息 -->
      <div class="login-footer">
        <div class="security-info">
          <i class="fas fa-shield-check"></i>
          <span>🏃‍♂️ 开启健康生活新篇章</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

export default {
  name: 'RegisterModal',
  props: {
    show: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:show', 'showLogin'],
  setup(props, { emit }) {
    const router = useRouter()

    const registerForm = ref({
      mobile: '',
      password: '',
      nickname: ''
    });
    const errorMessage = ref('');
    const successMessage = ref('');
    const isLoading = ref(false);

    const showLogin = () => {
      emit('update:show', false);
      emit('showLogin', true);
    };

    const handleSubmit = async () => {
      errorMessage.value = '';
      successMessage.value = '';
      isLoading.value = true;

      // 输入验证
      if (!registerForm.value.mobile.trim()) {
        errorMessage.value = '请输入手机号';
        isLoading.value = false;
        return;
      }

      if (!registerForm.value.password.trim()) {
        errorMessage.value = '请输入密码';
        isLoading.value = false;
        return;
      }

      if (!registerForm.value.nickname.trim()) {
          errorMessage.value = '请输入昵称';
          isLoading.value = false;
          return;
        }

      if (registerForm.value.password.length < 6) {
        errorMessage.value = '密码长度至少6位';
        isLoading.value = false;
        return;
      }

      try {
        // 调用后端注册API
        const response = await axios.post('/api/users/register', {
          mobile: registerForm.value.mobile,
          password: registerForm.value.password,
          nickname: registerForm.value.nickname
        })

        console.log('注册响应:', response.data) // 调试用

        // 根据后端的 Result 结构判断成功
        if (response.data && response.data.code === 200) {
          // 显示成功消息（绿色）
          successMessage.value = response.data.message || '注册成功！正在获取用户信息...';
          let userData = response.data.data || {};
          
          try {
            // 如果有用户ID，尝试获取完整用户信息
            const userId = userData.userId || userData.id || userData.uId
            if (userId) {
              console.log('RegisterModal - 调用getUserInfo获取最新用户信息，用户ID:', userId)
              const userInfoResponse = await axios.get(`/api/users/${userId}`)
              
              if (userInfoResponse.data && (userInfoResponse.data.code === 200 || userInfoResponse.data.success)) {
                userData = userInfoResponse.data.data;
                console.log('RegisterModal - 获取到的完整用户信息:', userData);
              }
            }
            
            // 如果没有完整信息，尝试自动登录
            if (!userData.token || !userData.nickname) {
              console.log('RegisterModal - 尝试自动登录获取完整信息')
              const loginResponse = await axios.post('/api/users/login', {
                mobile: registerForm.value.mobile,
                password: registerForm.value.password
              })

              // 根据后端的 Result 结构判断登录成功
              if (loginResponse.data && loginResponse.data.code === 200) {
                userData = loginResponse.data.data;
              } else {
                console.error('RegisterModal - 登录失败:', loginResponse.data.message || '未知错误')
                throw new Error('自动登录失败');
              }
            }

            // 保存用户信息
            localStorage.setItem('userToken', userData.token || 'user-registered-token');
              localStorage.setItem('userInfo', JSON.stringify(userData));
              localStorage.setItem('userId', userData.userId || userData.id || userData.uId);
            
            // 更新成功消息
            successMessage.value = '注册并登录成功！正在跳转...';
            
            // 延迟关闭模态框并重置表单
            setTimeout(() => {
              emit('update:show', false);
                registerForm.value.mobile = '';
                registerForm.value.password = '';
                registerForm.value.nickname = '';
              
              // 跳转到用户仪表板
              router.replace('/user/dashboard')
            }, 1500)
          } catch (error) {
            console.error('RegisterModal - 获取用户信息或自动登录失败:', error)
            errorMessage.value = '注册成功，但获取用户信息失败，请手动登录';
          }
        } else {
          // 显示错误消息（红色）
          errorMessage.value = response.data.message || '注册失败，请稍后重试';
        }
      } catch (error) {
          console.error('RegisterModal - 注册失败:', error);
          
          // 根据后端错误响应结构调整
          if (error.response && error.response.data) {
            // 后端返回的 Result 对象
            const result = error.response.data;
            if (result.message) {
              errorMessage.value = result.message;
            } else if (result.code !== 200) {
              errorMessage.value = result.message || '注册失败';
            } else {
              errorMessage.value = '注册失败，请稍后重试';
            }
          } else if (error.code === 'ECONNREFUSED' || error.message?.includes('ECONNREFUSED')) {
            errorMessage.value = '后端服务暂不可用，请检查服务是否启动'
          } else if (error.request) {
            errorMessage.value = '无法连接到服务器，请检查网络连接'
          } else {
            errorMessage.value = '注册过程中发生错误，请稍后重试'
          }
        } finally {
          // 确保无论如何都会重置加载状态
          setTimeout(() => {
            isLoading.value = false;
          }, 1500);
        }
    }

    return {
      registerForm,
      errorMessage,
      successMessage, // 返回成功消息
      isLoading,
      showLogin,
      handleSubmit
    }
  }
}
</script>

<style scoped>
/* 消息框基础样式 */
.message-box {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  border-radius: 8px;
  padding: 1rem;
  margin-bottom: 1.5rem;
  animation: slideIn 0.5s ease-in-out;
}

/* 错误消息样式 - 使用更具体的选择器 */
.message-box.error-message {
  background: rgba(220, 38, 38, 0.1);
  border: 1px solid rgba(220, 38, 38, 0.2);
}

/* 成功消息样式 - 使用更具体的选择器 */
.message-box.success-message {
  background: rgba(34, 197, 94, 0.1);
  border: 1px solid rgba(34, 197, 94, 0.2);
}

/* 图标样式 */
.message-box .message-icon {
  font-size: 0.9rem;
}

.message-box.error-message .message-icon {
  color: #dc2626;
}

.message-box.success-message .message-icon {
  color: #22c55e;
}

/* 文字样式 */
.message-box.error-message span {
  color: #ef4444;
  font-size: 0.85rem;
  font-weight: 500;
}

.message-box.success-message span {
  color: #22c55e;
  font-size: 0.85rem;
  font-weight: 500;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 艺术感图标样式 */
.artistic-icon {
  width: 60px;
  height: 60px;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon-shape {
  width: 100%;
  height: 100%;
  position: relative;
  transform-style: preserve-3d;
  animation: float-icon 3s ease-in-out infinite;
}

.fitness-symbol {
  width: 100%;
  height: 100%;
  position: relative;
}

/* 重量圆圈 */
.weight-circle {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 40px;
  height: 40px;
  border: 3px solid;
  border-color: #f093fb;
  border-radius: 50%;
  background: conic-gradient(
      from 0deg,
      transparent 0deg 180deg,
      rgba(240, 147, 251, 0.3) 180deg 360deg
  );
  animation: rotate-circle 8s linear infinite;
}

.weight-circle::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 20px;
  height: 20px;
  background: radial-gradient(circle, #f5576c 0%, #f093fb 100%);
  border-radius: 50%;
  box-shadow: 0 0 15px rgba(245, 87, 108, 0.5);
}

/* 能量波纹 */
.energy-wave {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 50px;
  height: 50px;
  border: 2px solid;
  border-color: rgba(240, 147, 251, 0.3);
  border-radius: 50%;
  animation: pulse-wave 2s ease-out infinite;
}

.energy-wave::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 60px;
  height: 60px;
  border: 1px solid;
  border-color: rgba(245, 87, 108, 0.2);
  border-radius: 50%;
  animation: pulse-wave 2s ease-out infinite 0.5s;
}

/* 运动线条 */
.motion-line {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 60px;
  height: 60px;
}

.motion-line::before,
.motion-line::after {
  content: '';
  position: absolute;
  background: linear-gradient(90deg, transparent, #f093fb, transparent);
  height: 2px;
  border-radius: 1px;
}

.motion-line::before {
  top: 10px;
  left: 0;
  width: 100%;
  transform: rotate(45deg);
  animation: shine-line 3s ease-in-out infinite;
}

.motion-line::after {
  bottom: 10px;
  left: 0;
  width: 100%;
  transform: rotate(-45deg);
  animation: shine-line 3s ease-in-out infinite 1.5s;
}

/* 动画定义 */
@keyframes float-icon {
  0%, 100% {
    transform: translateY(0px) rotate(0deg);
  }
  50% {
    transform: translateY(-5px) rotate(5deg);
  }
}

@keyframes rotate-circle {
  0% {
    transform: translate(-50%, -50%) rotate(0deg);
  }
  100% {
    transform: translate(-50%, -50%) rotate(360deg);
  }
}

@keyframes pulse-wave {
  0% {
    transform: translate(-50%, -50%) scale(0.8);
    opacity: 1;
  }
  100% {
    transform: translate(-50%, -50%) scale(1.2);
    opacity: 0;
  }
}

@keyframes shine-line {
  0%, 100% {
    opacity: 0.3;
    background: linear-gradient(90deg, transparent, rgba(240, 147, 251, 0.5), transparent);
  }
  50% {
    opacity: 1;
    background: linear-gradient(90deg, transparent, #f093fb, transparent);
  }
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(10px);
  animation: fadeIn 0.3s ease;
}

.modal-content {
  background: rgba(15, 23, 42, 0.8);
  backdrop-filter: blur(25px);
  border-radius: 20px;
  padding: 2.5rem 3rem;
  width: 90%;
  max-width: 480px;
  box-shadow:
      0 25px 50px rgba(0, 0, 0, 0.4),
      inset 0 1px 0 rgba(255, 255, 255, 0.1),
      0 0 0 1px rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.08);
  position: relative;
  overflow: hidden;
  animation: slideUp 0.3s ease;
}

.modal-content::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(90deg, transparent, rgba(255,255,255,0.4), transparent);
}

/* 背景效果 */
.background-effects {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.gradient-orbs {
  position: relative;
  width: 100%;
  height: 100%;
}

.orb {
  position: absolute;
  border-radius: 50%;
  filter: blur(60px);
  opacity: 0.15;
  animation: float 8s ease-in-out infinite;
}

.orb-1 {
  width: 200px;
  height: 200px;
  top: 10%;
  left: 10%;
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  animation-delay: 0s;
}

.orb-2 {
  width: 180px;
  height: 180px;
  top: 60%;
  right: 15%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  animation-delay: 2s;
}

.orb-3 {
  width: 160px;
  height: 160px;
  bottom: 20%;
  left: 20%;
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  animation-delay: 4s;
}

.grid-pattern {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image:
      linear-gradient(rgba(255,255,255,0.03) 1px, transparent 1px),
      linear-gradient(90deg, rgba(255,255,255,0.03) 1px, transparent 1px);
  background-size: 40px 40px;
  opacity: 0.3;
}

@keyframes float {
  0%, 100% { transform: translateY(0px) scale(1); }
  50% { transform: translateY(-20px) scale(1.05); }
}

/* 顶部区域 */
.modal-header {
  text-align: center;
  margin-bottom: 2rem;
  position: relative;
}

.logo-container {
  margin-bottom: 1.5rem;
}

.logo-wrapper {
  display: inline-flex;
  align-items: center;
  gap: 1rem;
  background: rgba(255, 255, 255, 0.05);
  padding: 1rem 1.5rem;
  border-radius: 16px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.logo-text h1 {
  font-size: 1.75rem;
  font-weight: 700;
  background: linear-gradient(135deg, #fff 0%, #cbd5e1 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  margin: 0;
  line-height: 1.2;
}

.logo-text span {
  font-size: 0.75rem;
  color: #94a3b8;
  font-weight: 600;
  letter-spacing: 1px;
}

.welcome-text h2 {
  font-size: 1.5rem;
  font-weight: 600;
  color: #f8fafc;
  margin: 0 0 0.5rem 0;
}

.welcome-text p {
  color: #94a3b8;
  font-size: 0.95rem;
  margin: 0;
  font-weight: 400;
}

.close-btn {
  position: absolute;
  top: 1rem;
  right: 1rem;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  color: #94a3b8;
  padding: 0.5rem;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 1.2rem;
  width: 35px;
  height: 35px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  color: #f8fafc;
  border-color: rgba(255, 255, 255, 0.2);
}

/* 表单样式 */
.login-form {
  margin-bottom: 1.5rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

.input-container {
  position: relative;
}

.input-icon {
  position: absolute;
  left: 1rem;
  top: 50%;
  transform: translateY(-50%);
  color: #64748b;
  font-size: 1rem;
  z-index: 2;
  transition: color 0.3s ease;
}

.form-input {
  width: 100%;
  padding: 1.125rem 1rem 1.125rem 3rem;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-radius: 12px;
  font-size: 1rem;
  color: #f8fafc;
  transition: all 0.3s ease;
  position: relative;
  z-index: 1;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.form-input::placeholder {
  color: #64748b;
}

.form-input:focus {
  outline: none;
  background: rgba(255, 255, 255, 0.08);
  border-color: rgba(240, 147, 251, 0.6);
  box-shadow: 0 0 0 3px rgba(240, 147, 251, 0.15);
}

.form-input:focus + .input-border {
  opacity: 1;
  transform: scaleX(1);
}

.form-input:focus ~ .input-highlight {
  opacity: 1;
  transform: scaleX(1);
}

.input-border {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 2px;
  background: linear-gradient(90deg, #f093fb, #f5576c);
  opacity: 0;
  transform: scaleX(0);
  transition: all 0.3s ease;
  border-radius: 0 0 12px 12px;
  z-index: 2;
}

.input-highlight {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, rgba(240, 147, 251, 0.1), rgba(245, 87, 108, 0.1));
  border-radius: 12px;
  opacity: 0;
  transform: scaleX(0);
  transition: all 0.3s ease;
  z-index: 0;
}

/* 按钮样式 */
.form-buttons {
  display: flex;
  gap: 1rem;
  margin-top: 2rem;
}

.login-button {
  flex: 2;
  padding: 1.125rem;
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  box-shadow: 0 8px 25px rgba(240, 147, 251, 0.3);
}

.login-button:hover:not(.loading) {
  transform: translateY(-2px);
  box-shadow: 0 12px 30px rgba(240, 147, 251, 0.4);
}

.login-button:active {
  transform: translateY(0);
}

.login-button.loading {
  cursor: not-allowed;
  opacity: 0.8;
}

.button-text, .button-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  position: relative;
  z-index: 2;
}

.button-shine {
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
  transition: left 0.5s ease;
}

.login-button:hover .button-shine {
  left: 100%;
}

.register-btn {
  flex: 1;
  padding: 1.125rem;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  color: #94a3b8;
  border-radius: 12px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
}

.register-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  color: #f8fafc;
  border-color: rgba(255, 255, 255, 0.2);
  transform: translateY(-2px);
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  25% { transform: translateX(-5px); }
  75% { transform: translateX(5px); }
}

/* 底部信息 */
.login-footer {
  display: flex;
  justify-content: center;
  align-items: center;
  padding-top: 1.5rem;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.security-info {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: #64748b;
  font-size: 0.8rem;
  font-weight: 500;
}

.security-info i {
  color: #10b981;
}

/* 动画 */
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .modal-content {
    padding: 2rem 1.5rem;
    margin: 1rem;
  }

  .logo-wrapper {
    flex-direction: column;
    gap: 0.75rem;
    text-align: center;
  }

  .form-buttons {
    flex-direction: column;
  }
}

@media (max-width: 480px) {
  .modal-content {
    padding: 1.5rem 1.25rem;
  }

  .logo-text h1 {
    font-size: 1.5rem;
  }

  .welcome-text h2 {
    font-size: 1.25rem;
  }
}
</style>